﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StockAnalysisModel;
using System.Threading;
using Wusong.Dal.EF;
using Wusong.Dal.SQLLite;
using System.Data.Objects;


namespace QQStockInfoReader
{
    public partial class AreaAnalysisMainForm : Form
    {
        ObjectContext dbContext;
        public AreaAnalysisMainForm()
        {
            InitializeComponent();
            dbContext = new StockAnalysisModel.StockAnalysisEntities();
        }

        private void AreaAnalysisMainForm_Load(object sender, EventArgs e)
        {
            BindAreaChoice();
            RefreshData();
        }

        private void BindAreaChoice()
        {
            CheckBox cbArea;
            IEnumerable<string> areaFields = AreaStockReader.GetAreaFileds();
            bool isFirstSelected = false;
            foreach (string field in areaFields)
            {
                cbArea = new CheckBox();
                cbArea.AutoSize = false;
                //cbArea.Width = 75;
                cbArea.Height = 45;
                cbArea.Text = field;
                cbArea.FlatStyle = FlatStyle.Popup;
                if (!isFirstSelected)
                {
                    isFirstSelected = true;
                    cbArea.Checked = true;
                }
                cbArea.CheckedChanged += new EventHandler((object sender, EventArgs e) => { RefreshData(); });
                this.flpAreaFields.Controls.Add(cbArea);
            }
        }

        private void RefreshData()
        {
            try
            {
                //获取选中区域
                string[] ares = GetSelectedAreas();
                //查询数据
                var datas = QueryData(ares);
                //绑定数据
                BindData(datas.ToList(), ares);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private IEnumerable<StockDailyInfo> QueryData(string[] ares)
        {
            #region 准备参数
            DateTime stTime = DateTime.Now;
            DateTime stEndTime = DateTime.Now;
            #endregion
            try
            {
                Wusong.Dal.Inf.IObjDAO<StockDailyInfo> dao = new EF4DAO<StockDailyInfo>(dbContext);
                //var infos = dao.LoadEntites((StockDailyInfo info) => { return (info.RecordDate.Value.Date >= stTime.Date && info.RecordDate.Value.Date <= stEndTime.Date && ares.Contains(info.AreaFiledName.Trim())); });
                //var infos = dao.LoadEntites((StockDailyInfo info) => { return (info.RecordDate.Value.Date >= stTime.Date && info.RecordDate.Value.Date <= stEndTime.Date); });
                //infos = dao.LoadEntites((StockDailyInfo info) => { return (info.RecordDate.Value.Date >= stTime.Date && info.RecordDate.Value.Date <= stEndTime.Date && info.StockAreaName.Trim() == "累计涨幅"); });
                //string queryStr = string.Format("select *  from StockDailyInfo where RecordDate>=@stTime and RecordDate<=@endTime and  StockAreaName in ('{0}')", string.Join(",", ares));

                ////var infos = dbContext.ExecuteStoreQuery<StockDailyInfo>(queryStr, new ObjectParameter("stTime", stTime.Date), new ObjectParameter("endTime", stEndTime.Date));
                //var infos = dbContext.ExecuteStoreQuery<StockDailyInfo>(queryStr, SQLLiteDNet.AddParameter("stTime", stTime.Date), SQLLiteDNet.AddParameter("endTime", stEndTime.Date));
                string queryStr = string.Format("select *  from StockDailyInfo where RecordDate>='{0}' and RecordDate<='{1}' and  AreaFiledName in ('{2}')", stTime.ToString("yyyy-MM-dd"), stEndTime.AddDays(1).ToString("yyyy-MM-dd"), string.Join("','", ares));
                var infos = dbContext.ExecuteStoreQuery<StockDailyInfo>(queryStr, SQLLiteDNet.AddParameter("stTime", stTime.Date), SQLLiteDNet.AddParameter("endTime", stEndTime.Date));

                return infos;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return null;
        }

        private string[] GetSelectedAreas()
        {
            IList<string> lstArea = new List<string>();
            //获取选中区域
            foreach (Control ctl in this.flpAreaFields.Controls)
            {
                CheckBox area = ctl as CheckBox;
                if (area.Checked)
                {
                    lstArea.Add(area.Text);

                }
            }
            return lstArea.ToArray();
        }


        private void BindData(IEnumerable<StockDailyInfo> dataSource, string[] ares)
        {
            DataTable dt = AreaStockReader.ConvertOjbsToDataTable(dataSource, ares);
            this.dataGridView1.DataSource = dt;
            this.dataGridView1.AutoGenerateColumns = true;
            this.dataGridView1.Refresh();
        }


        private void AreaAnalysisMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (dbContext != null)
            {
                dbContext.Dispose();
            }
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                if ((bool)row.Cells["涨"].FormattedValue)
                {
                    row.DefaultCellStyle.BackColor = Color.Red;
                }
                else
                {
                    row.DefaultCellStyle.BackColor = Color.Gray;

                }
            }
        }
    }
}
